package com.sc.base.common.utils;

import com.sc.base.apiutils.api.ErrorInfo;
import com.sc.base.common.spring.utils.DefaultErrorInfoConverter;
import com.sc.base.common.spring.utils.ErrorInfoConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.util.Map;

/**
 * @Author liuwei
 * @Date 2021/2/2317:21
 */
public abstract class SpringViewUtils {

    private static final Logger logger = LoggerFactory.getLogger(SpringViewUtils.class);

    private static ErrorInfoConverter defaultErrorInfoConverter = new DefaultErrorInfoConverter();

    public static ModelAndView createJsonErrorView(ErrorInfo error, ErrorInfoConverter errorInfoConverter) {
        ModelAndView mav = new ModelAndView();
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        Map<String, Object> errorInfoMap = null;
        if(errorInfoConverter != null) {
            try {
                errorInfoMap = errorInfoConverter.convertErrorInfoToMap(error);
            } catch (Exception e) {
                logger.error("", e);
            }
        }
        if(errorInfoMap == null) {
            errorInfoMap = defaultErrorInfoConverter.convertErrorInfoToMap(error);
        }
        view.setAttributesMap(errorInfoMap);
        mav.setView(view);
        return mav;
    }


}
